<template>
  <div>
    <div class="modal-header">
      <div class="ant-modal-title">
        {{ l('ChangeTenant') }}
      </div>
    </div>

    <div class="modal-body">
      <a-form :form="form" @submit="handleSubmit" layout="vertical">
        <a-form-item :label="l('TenancyName')">
          <a-input v-model:value="form.tenancyName" />
          <a-alert :message="l('LeaveEmptyToSwitchToHost')" type="warning" show-icon />
        </a-form-item>
      </a-form>
    </div>

    <div class="modal-footer">
      <a-button @click="close()">
        {{ l('Cancel') }}
      </a-button>
      <a-button @click="handleSubmit" type="primary">
        {{ l('Save') }}
      </a-button>
    </div>
  </div>
</template>

<script lang="ts">
  import { ModalComponentBase } from '/@/shared/component-base';
  import { AccountServiceProxy, IsTenantAvailableInput } from '/@/shared/service-proxies';
  import { AppTenantAvailabilityState } from '/@/abpPro/AppEnums';
  import { defineComponent } from 'vue';

  export default defineComponent({
    name: 'TenantChangeModal',
    mixins: [ModalComponentBase],
    props: {
      tenancyNames: {
        type: String, // 实际传过来的类型
      },
    },
    data() {
      return {
        form: new IsTenantAvailableInput(),
        tenancyName: undefined,
        accountServiceProxy: new AccountServiceProxy(),
      };
    },
    watch: {
      tenancyName(val) {
        if (val) {
          this.form.tenancyName = val;
        }
      },
    },
    created() {
      this.fillServiceProxy();
      this.form.tenancyName = this.tenancyNames;
    },
    methods: {
      handleSubmit(e) {
        e.preventDefault();

        if (this.form.tenancyName === this.tenancyName) {
          this.close();
          return;
        }
        if (!this.form.tenancyName || this.form.tenancyName === '') {
          this.abp.multiTenancy.setTenantIdCookie(undefined);
          this.close();
          location.reload();
          return;
        }

        this.accountServiceProxy.isTenantAvailable(this.form).then((result) => {
          switch (result.state) {
            case AppTenantAvailabilityState.Available:
              this.abp.multiTenancy.setTenantIdCookie(result.tenantId);
              this.success();
              window.location.reload();
              return;
            case AppTenantAvailabilityState.InActive:
              this.message.warn(this.l('TenantIsNotActive', this.form.tenancyName));

              break;
            case AppTenantAvailabilityState.NotFound: // NotFound
              this.message.warn(this.l('ThereIsNoTenantDefinedWithName{0}', this.form.tenancyName));
              break;
          }
        });
      },
    },
  });
</script>

<style lang="less" scoped>
  .ant-alert {
    padding: 8px 0;
  }
  html[data-theme='light'] .ant-alert-warning {
    background: none;
    border: none;
  }
  .modal-body {
    padding: 0 100px;
  }
</style>
